package com.etown.util;

import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.etown.dao.DBPool;
import com.etown.lucene.FileScheduler;
import com.etown.lucene.FileSchedulerTask;
import com.etown.lucene.TimeStep;

/**
 * 系统参数初始化Servlet
 * 系统启动时会自动执行此Servlet的init方法
 * @author 大漠穷秋
 */
@SuppressWarnings("serial")
public class EnvInitServlet extends HttpServlet {
	private String webRootDir;

	public static final String WEB_HOME = "web.home";

	private static Logger log = Logger.getLogger(EnvInitServlet.class);

	//设置日志记录跟踪器
	public static Logger etownlogger = Logger.getLogger("stdout");//设置事件日志记录器

	public void init() {
		//解析应用根目录
		parsewebRootDir();

		//初始化Log4j日志
		configLog4j();

		//加载配置的系统参数 
		loadProperties();

		//初始化数据库连接
		initDBConn();
		
		//初始化Lucene相关
		monitorLuceneTxTFile();
	}

	/**
	 * 解析应用根目录
	 *
	 */
	private void parsewebRootDir() {
		webRootDir = getServletContext().getRealPath("/");
		System.setProperty(WEB_HOME, webRootDir);
	}

	/**
	 * 初始化Log4j日志
	 *
	 */
	private void configLog4j() {
		String file = getInitParameter("log4j-init-file");
		if (file != null) {
			PropertyConfigurator.configure(webRootDir + file);
		}
		etownlogger = Logger.getLogger("stdout");
	}

	/**
	 *加载配置的系统参数 
	 *
	 */
	private void loadProperties() {
		ServletContext sc = this.getServletContext();
		Enumeration e = sc.getInitParameterNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			String value = sc.getInitParameter(name);
			System.setProperty(name, value);
			log.info("添加系统参数名：" + name + "；参数值：" + value);
		}
	}

	/**
	 * 初始化数据库连接
	 *
	 */
	private void initDBConn(){
		DBPool.initConn(10);
	}
	
	/**
	 * 初始化Lucene引擎
	 *
	 */
	private void monitorLuceneTxTFile() {
		//创建local_files文件监控任务
		FileSchedulerTask fileSchedulerTask = new FileSchedulerTask(System
				.getProperty("web.home")
				+ System.getProperty("luceneLocalFolder"));
		FileScheduler fileScheduler = new FileScheduler();
		fileScheduler.schedule(fileSchedulerTask, new TimeStep());
	}

}
